from django.http import JsonResponse
from django.views import View
from .models import Catalog, SKU, SKUImage, SPU, SPUSaleAttr, SaleAttrValue,SKUSpecValue,SPUSpec
from django.conf import settings
from utils.cache_dec import cache_check


# # Create your views here.
class GoodsIndexView(View):
    def get(self, request):
        """首页展示视图逻辑"""
        # 获取所有类别，
        all_catalog = Catalog.objects.all()

        data = []
        for cata in all_catalog:
            # cata -->三个键值对
            cata_dict = {}
            cata_dict["catalog_id"] = cata.id
            cata_dict["catalog_name"] = cata.name
            cata_dict["sku"] = []
            spus = SPU.objects.filter(catalog=cata).values("id")  # 查到所有的id
            skus = SKU.objects.filter(spu__in=spus, is_launched=True)
            for sku in skus:
                sku_dict = {
                    "skuid": sku.id,
                    "caption": sku.caption,
                    "name": sku.name,
                    "price": sku.price,
                    "image": str(sku.default_image_url)
                }
                cata_dict["sku"].append(sku_dict)
            data.append(cata_dict)
        result = {"code": 200, "data": data, "base_url": settings.PIC_URL}
        return JsonResponse(result)


class GoodsDetailView(View):
    @cache_check(key_prefix="gd",key_param="sku_id",cache="goods_detail",expire=60)
    def get(self, request, sku_id):
        """
        详情页展示视图逻辑
        :param sku_id: 商品id
        """
        print("详情页数据来自mysql")
        try:
            sku_item = SKU.objects.get(id=sku_id)
        except Exception as e:
            print("无此商品", e)
            return JsonResponse({"code": 20100, "error": "无此商品"})

        data = {}
        # 类1：类别id 类别name
        sku_cata = sku_item.spu.catalog
        data["catalog_id"] = sku_cata.id
        data["catalog_name"] = sku_cata.name

        # 类2：sku
        data["name"] = sku_item.name
        data["caption"] = sku_item.caption
        data["price"] = sku_item.price
        data["image"] = str(sku_item.default_image_url)
        data["spu"] = sku_item.spu.id

        # 类3：详情图片
        image_query = SKUImage.objects.filter(sku=sku_item)
        if image_query:
            data["detail_image"] = str(image_query[0].image)
        else:
            data["detail_image"] = ""

        # 类4：销售属性
        sale_attr_query = sku_item.sale_attr_value.all()
        data["sku_sale_attr_id"] = [i.spu_sale_attr.id for i in sale_attr_query]
        data["sku_sale_attr_names"] = [i.spu_sale_attr.name for i in sale_attr_query]

        # 类5：销售属性值
        data["sku_sale_attr_val_id"] = [i.id for i in sale_attr_query]
        data["sku_sale_attr_val_names"] = [i.name for i in sale_attr_query]

        # 体现销售属性和销售属性值的关系
        sku_all_sale_attr_vals_id = {}
        sku_all_sale_attr_vals_names = {}
        for id in data["sku_sale_attr_id"]:
            value_query = SaleAttrValue.objects.filter(spu_sale_attr=id)
            sku_all_sale_attr_vals_id[id] = [i.id for i in value_query]
            sku_all_sale_attr_vals_names[id] = [i.name for i in value_query]
        #添加到大字典中
        data["sku_all_sale_attr_vals_id"] = sku_all_sale_attr_vals_id
        data["sku_all_sale_attr_vals_names"] = sku_all_sale_attr_vals_names

        #类6和类7：规格属性名和规格属性值
        spec= {}
        spec_query = SKUSpecValue.objects.filter(sku=sku_item)
        for spec_q in spec_query:
            key = spec_q.spu_spec.name
            value = spec_q.name
            spec[key] = value

        data["spec"] = spec


        result = {
            "code": 200,
            "data": data,
            "base_url": settings.PIC_URL
        }
        return JsonResponse(result)



